let { user, surveyname, surveydata, grade,userquestionnaire } = require('../models');
let auth = require('../utils/auth')

let index_fn = async (ctx, next) => {
    let username = ctx.session.userName;
    let userId = ctx.session.userId;

    //所有的标题
    let msgs = JSON.parse(JSON.stringify(await surveyname.findAll({
        order: [
            ['id', 'desc']
        ],
        where: {
            isenable: 0
        }
        //limit: 5, offset: 0
    })));
    let obj = {
        username,
        msgs,
        userId,
    }

    ctx.render('index.html', obj);
};


let login_fn = async (ctx, next) => {
    ctx.render('login.html');
};




let loginDone_fn = async (ctx, next) => {
    let uid = ctx.request.body.username.trim() || '';
    let pwd = ctx.request.body.password.trim() || '';

    let res = '';

    if (uid.length > 0 && pwd.length > 0) {
        let row = await user.findOne({
            where: {
                username: uid,
                password: pwd
            }
        });
        let dt = JSON.stringify(row);
        if (dt !== 'null') {
            ctx.session.userId = row.id;
            ctx.session.userName = row.username;
            res = { code: 200, msg: '登录成功' };
        } else {
            res = { code: 1000, msg: '用户名或密码错误，请确认后重试' };
        }

    } else {
        res = { code: 1000, msg: '用户名和密码不能为空' };
    }
    ctx.body = JSON.stringify(res);
};


let registerDone_fn = async (ctx, next) => {
    let uid = ctx.request.body.username.trim() || ''
    let pwd = ctx.request.body.password.trim() || '';
    let confirmpwd = ctx.request.body.confirmpassword.trim() || '';

    let res = '';

    if (uid.length > 0 && pwd.length > 0 && pwd === confirmpwd) {
        let row = await user.findOne({
            where: {
                username: uid
            }
        });
        let dt = JSON.stringify(row);
        if (dt === 'null') {
            var u1 = await user.create({
                username: uid,
                password: pwd,
            });
            let u2 = JSON.stringify(u1);
            if (u2 !== 'null') {
                res = { code: 200, msg: '用户注册成功' };
            } else {
                res = { code: 1000, msg: '因为服务器或者网络原因，用户未注册成功' };
            }
        } else {
            res = { code: 1000, msg: "当前用户名已经注册，请确认后重试" }
        }
    } else {
        res = { code: 1000, msg: '用户名和密码不能为空，且密码应该一致' };
    }
    ctx.body = JSON.stringify(res);
};
// 注销
let logout_fn = async (ctx, next) => {
    ctx.session = null;
    ctx.body = { code: 200, msg: '注销成功' };
}



let surveyName_fn = async (ctx, next) => {
    let onetitle = ctx.request.body.onetitle || '';
    let onedescription = ctx.request.body.onedescription || '';
    let userId = ctx.session.userId;
    let res = '';

    if (onetitle.length > 0) {
        let createtitle = await surveyname.create({
            fromUserId: userId,
            title: onetitle,
            description: onedescription
        });

        let data = JSON.stringify(createtitle);
        if (data !== 'null') {
            ctx.session.titleid = createtitle.id;
            res = { code: 200, msg: '调查名称成功' };
        } else {
            res = { code: 1000, msg: '调查名称未成功' };
        }
    } else {
        res = { code: 1000, msg: '标题不能为空' };
    }

    ctx.body = JSON.stringify(res);
}
//问卷问题发表
let pronlem_fn = async (ctx, next) => {
    let oneproblem = ctx.request.body.oneproblem || [];
    // console.log(oneproblem);
    let titleId = ctx.session.titleid;

    let arr = []
    var bool = arr.every(function (element) {
        return element.length > 0;
      });
      if(bool==true){
        oneproblem.forEach(item => {
            arr.push({
                question: item,
                surveyid: titleId
            })
        })
      }
  


    await surveydata.bulkCreate(arr)


    // let data = JSON.stringify(pronlem);

    ctx.body = { code: 200, msg: '发表成功' };
}
//创建问卷页面
let addquestionnaire_fn = async (ctx, next) => {


    //所有的标题
    let datas = JSON.parse(JSON.stringify(await surveydata.findAll({
        order: [
            ['id', 'desc']
        ]
    })));

    // console.log(datas);
    let obj = {
        datas,
    }
    ctx.render('addquestionnaire.html', obj);
}



let answer_fn = async (ctx, next) => {

    let dt = ctx.request.body.titlesId || '';
    ctx.session.answerid = dt;
    ctx.body = { code: 200, };

}
//回答页面
let addanswer_fn = async (ctx, next) => {
    var answerid = ctx.session.answerid;


    //查询数据库surveyid=answerid
    let msgs = JSON.parse(JSON.stringify(await surveydata.findAll({
        where: {
            surveyid: answerid
        }
    })));

    // 查询出来的说说的id（如果有分页，则应该是10条说说的id）
    let msgIds = [];

    msgs.forEach(item => {
        msgIds.push(item.id);
    });

    ctx.session.quesid = msgIds;
    let obj = {
        msgs,
    }
    ctx.render('addanswer.html', obj);

}

// 提交问卷分数
var submitscore_fn = async (ctx, next) => {
    //评的分数
    let gradess = ctx.request.body.electronicIds || [];
    //用户id
    let userId = ctx.session.userId;
    //问题id
    let questionid = ctx.session.quesid;
    //问卷id
    var answerid = ctx.session.answerid;

    //console.log(answerid);

    let rulst = []
        let row = await userquestionnaire.findOne({
            where: {
                userid: userId,
                titleid:answerid
            }
        });
        let dt = JSON.stringify(row);
        if (dt === 'null') {
            gradess.forEach((item, index) => {
                rulst.push({
        
                    score: item,
                    questionid: questionid[index],
                    fillinuserid: userId
        
                })
            })

            await userquestionnaire.create({
                userid: userId,
                titleid: answerid,
            });
           
           let u2 =await grade.bulkCreate(rulst);
          
            if (u2 !== 'null') {
                res = { code: 200, msg: '问卷发表成功' };
            } else {
                res = { code: 1000, msg: '因为服务器或者网络原因，用户未发表成功' };
            }
        } else {
            res = { code: 1000, msg: "当前用户名已发表" }
        }
   

    // let rulst = []

    // gradess.forEach((item, index) => {
    //     rulst.push({

    //         score: item,
    //         questionid: questionid[index],
    //         fillinuserid: userId

    //     })
    // })
    // await grade.bulkCreate(rulst);


    ctx.body = JSON.stringify(res);

}

var myindexDon_fn = async (ctx, next) => {

    let userId = ctx.request.body.userId || '';

    ctx.session.myid = userId;


    ctx.body = { code: 200, msg: '发表成功' };
}



var myindex_fn = async (ctx, next) => {

    let username = ctx.session.userName;
    let myuserId = ctx.session.userId;

    let userId = ctx.session.myid;

    //查询数据库fromUserId=userId
    let msgs = JSON.parse(JSON.stringify(await surveyname.findAll({
        where: {
            fromUserId: userId,
            isenable: 0
        }
    })));
    let obj = {
        msgs,
        username,
        myuserId,
    }
    ctx.render('myindex.html', obj);

}
//删除
var deleteDon_fn = async (ctx, next) => {
    let deleteId = ctx.request.body.deleteId || '';
    console.log(deleteId);

    await surveyname.update({
        isenable: "1"
    }, {
        where: {
            id: deleteId,
        }
    }
    );

    ctx.body = { code: 200, };
}


//管理
var administration_fn = async (ctx, next) => {

    let username = ctx.session.userName;
    let userId = ctx.session.userId;
    let titleIds=[];
     //查询数据库fromUserId=userId
     let msgs = JSON.parse(JSON.stringify(await surveyname.findAll({
        where: {
            fromUserId:userId,
        }
    })));

    msgs.forEach(item=>{
       titleIds.push(item.id);
    });

  //  console.log(titleIds);
  let userAll=await surveydata.findAll({
    where:{
        surveyid:titleIds
    }
});


    
var dt=JSON.parse(JSON.stringify(userAll));


msgs.forEach((item)=>{
   
let tlid=dt.filter(row=>{
 
    return item.id=== row.surveyid
})[0];

   item.question=tlid;
  // console.log(tlid);
})




//console.log(msgs);




    let obj = {
        msgs,
        username,
        
    }
    ctx.render('administration.html',obj);
}

var administrationDon_fn = async (ctx, next) => {
    let myuserId = ctx.request.body.myuserId || '';
    

    ctx.body = { code: 200, };
}


//修改密码
var passwordDon_fn = async (ctx, next) => {
    let password = ctx.request.body.password.trim()|| '';
    let confirmpassword = ctx.request.body.confirmpassword.trim() || '';
   
    //用户id
    let myuserId = ctx.session.userId;
 
    if (password.length > 0 && confirmpassword.length > 0 && password===confirmpassword) {
        await user.update({
            password:confirmpassword,
        }, {
            where: {
                id: myuserId,
            }
        }
        );
    }else{
        res = { code: 1000, msg: '请确认二次密码一致或不能为空' };
    }

    ctx.body = { code: 200, };
}


module.exports = {
    '/': ['get', auth, index_fn],
    '/login': ['get', auth, login_fn],
    '/logout': ['post', auth, logout_fn],
    '/loginDone': ['post', loginDone_fn],
    '/registerDone': ['post', registerDone_fn],
    '/addquestionnaire': ['get', addquestionnaire_fn],
    '/surveyName': ['post', surveyName_fn],
    '/pronlem': ['post', pronlem_fn],
    '/answer': ['post', answer_fn],
    '/addanswer': ['get', addanswer_fn],
    '/submitscore': ['post', submitscore_fn],
    '/myindexDon': ["post", myindexDon_fn],
    '/myindex': ["get",auth, myindex_fn],
    '/deleteDon': ["post", deleteDon_fn],
    '/administrationDon': ["post", administrationDon_fn],
    '/administration': ["get",auth,administration_fn],
    '/passwordDon': ["post", passwordDon_fn],
}